package org.third.security.cert;

import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.DERUTF8String;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.third.common.utils.StreamUtils;

public class CustomX509UserPrincipalNameExtractor {

    private static final Logger logger = LoggerFactory.getLogger(CustomX509UserPrincipalNameExtractor.class);

    public String determineUserPrincipalName(Object otherNameExtensionField) {
        ASN1InputStream decoder = null;
        try {
            decoder = new ASN1InputStream((byte[]) otherNameExtensionField);
            ASN1Primitive encoded = decoder.readObject();
//            encoded = ((DERSequence) encoded).getObjectAt(1);
            encoded = ((DERTaggedObject) encoded).getObject();
            encoded = ((DERTaggedObject) encoded).getObject();
            return ((DERUTF8String) encoded).getString();
        } catch (Exception e) {
            logger.warn("Cannot parse the user principal name. ");
            return null;
        } finally {
            StreamUtils.closeQuietly(decoder);
        }
    }
}
